package com.dcits.agent.loader;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @className: SmartClassLoader
 * @description:
 * @author: caoyangjie
 * @date: 2025/6/21
 **/
public class SmartClassLoader extends ClassLoader {
    private static class SmartClassLoaderHolder {
        private static final SmartClassLoader instance = new SmartClassLoader();
    }
    public static ConcurrentHashMap<String, Class> cacheClass = new ConcurrentHashMap<>();
    public static ModifyClassLoader modifyClassLoader;

    private SmartClassLoader() {
        super(SmartClassLoader.class.getClassLoader());
    }

    public Class defineClassFromBytes(String className, byte[] classBytes) {
        if( modifyClassLoader == null ) {
            modifyClassLoader = new ModifyClassLoader(this);
        }
        return cacheClass.computeIfAbsent(className, clazz-> modifyClassLoader.defineClassFromBytes(className, classBytes));
    }

    public Class<?> findClass(String name) {
        return cacheClass.get(name);
    }

    // 当前类需要一个单例方法
    public static SmartClassLoader getInstance() {
        return SmartClassLoaderHolder.instance;
    }
}
